package com.mz.ozy;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.bumptech.glide.request.target.ViewTarget;
import com.danikula.videocache.HttpProxyCacheServer;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.net.RetrofitUtils;
import com.mz.ozy.utils.ImageLoader;
import com.mz.ozy.utils.QiNiuManger;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.widget.CustomHeaderView;
import com.previewlibrary.ZoomMediaLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.sobot.chat.ZCSobotApi;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;

import cn.jpush.android.api.JPushInterface;

public class WpkApp extends Application {
    public static Context mcx;
    public static WpkApp ctx;
    //屏幕信息
    public static int screenWidth;
    public static int screenHeight;

    @Override
    public void onCreate() {
        super.onCreate();
        ctx = this;
        mcx = getApplicationContext();
        UMConfigure.preInit(this, Constants.KEY.UM_APP_KEY, "release");
    }

    public void initLaunch(){

        CrashReport.initCrashReport(getApplicationContext(), "27ff14dc98", false);

        //Glide设置别的get/set tag id，以免占用View默认的
        ViewTarget.setTagId(R.id.tag_glide);
        ZoomMediaLoader.getInstance().init(new ImageLoader());
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        Constants.tokenId = SPUtils.getInstance(this).getString(Constants.PREE.TOKEN_ID, "");
        MultiDex.install(this);
        QiNiuManger.getInstance().init();
        ZXingLibrary.initDisplayOpinion(this);
        disableAPIDialog();
        initScreenInfo();
        initJPush();
        initBaiduMap();
        registToWX();
        RetrofitUtils.handleSSLHandshake();
        UMConfigure.init(this, Constants.KEY.UM_APP_KEY
                , "umeng", UMConfigure.DEVICE_TYPE_PHONE, null);

        // UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        //58edcfeb310c93091c000be2 5965ee00734be40b580001a0
//        PlatformConfig.setWeixin(Constants.KEY.WX_APP_ID, Constants.KEY.WX_APP_KEY);
        PlatformConfig.setWeixin("wx4a31dea55c39e742", "c3119280ab6c235361129449f3a21a5e");
        /*
        APPID：wx800a4b8ced3ed43b
APSecret：b88b4c3e7577d7f5d838517c60b3b819
         */
        PlatformConfig.setQQZone(Constants.KEY.QQ_APP_ID, Constants.KEY.QQ_APP_KEY);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        Constants.uid = SPUtils.getInstance(this).getString(Constants.PREE.UID, "");
        String is_login = SPUtils.getInstance(this).getString(Constants.SPName.IS_LOGIN, "");
        if ("1".equals(is_login)) {
            Constants.isLogin = true;
        }
        if (!TextUtils.isEmpty(Constants.uid)){
            JPushInterface.setAlias(getApplicationContext(), 1, Constants.uid);
        }
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setHeaderHeight(80);
                return new CustomHeaderView(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        initSobotApp();
    }

    private void initJPush() {
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
    }

    private void initSobotApp() {
        ZCSobotApi.initSobotSDK(getApplicationContext(), "f970b1112b8447b6abe76c7acbf450cd", "");
    }

    private void initBaiduMap() {
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(getApplicationContext());
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.BD09LL);
    }

    private void registToWX() {
        //AppConst.WEIXIN.APP_ID是指你应用在微信开放平台上的AppID，记得替换。
        Constants.sWxApi = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        // 将该app注册到微信
        Constants.sWxApi.registerApp(Constants.APP_ID);
    }

    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        WpkApp app = (WpkApp) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer(this);
    }

    /**
     * 初始化屏幕信息
     */
    private void initScreenInfo() {
        //屏幕信息
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
    }


    private void disableAPIDialog() {
        if (Build.VERSION.SDK_INT < 28) return;
        try {
            Class clazz = Class.forName("android.app.ActivityThread");
            Method currentActivityThread = clazz.getDeclaredMethod("currentActivityThread");
            currentActivityThread.setAccessible(true);
            Object activityThread = currentActivityThread.invoke(null);
            Field mHiddenApiWarningShown = clazz.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
